<template>
  <div>
    <el-form
      style="width: 500px"
      :model="form"
      label-width="120px"
      :rules="rules"
    >
      <el-form-item label="链接" prop="link">
        <el-input v-model="form.link" placeholder="请输入链接" />
      </el-form-item>
      <el-form-item label="提示" prop="alt">
        <el-input v-model="form.alt" placeholder="请输入提示" />
      </el-form-item>
      <el-form-item label="图片">
        <input type="file" placeholder="请上传文件" @change="fn" />
      </el-form-item>
      <el-form-item>
        <el-image
          v-if="form.img"
          style="width: 100px; height: 100px"
          :src="form.img"
          :zoom-rate="1.2"
          :preview-src-list="[form.img]"
          fit="cover"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="submit">提交</el-button>
      </el-form-item>
    </el-form>
    <!-- <img v-if="form.img" :src="form.img" alt="" /> -->
  </div>
</template>

<script>
import { bannerAddApi } from "@/api/index.js";

export default {
  data() {
    return {
      form: {
        link: "",
        alt: "",
        img: "",
      },
      rules: {
        link: [
          {
            required: true,
            message: "Please input link",
            trigger: "blur",
          },
        ],
        alt: [
          {
            required: true,
            message: "Please input alt",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    fn(e) {
      // console.log(e.target.files[0]);
      // 要将图片转成base64,不用记的
      const render = new FileReader();
      render.readAsDataURL(e.target.files[0]);
      render.onload = (event) => {
        // console.log(event.target.result);
        this.form.img = event.target.result;
      };
    },
    async submit() {
      const res = await bannerAddApi(this.form);
      if (res) {
        ElMessage({
          message: res.message,
          type: "success",
        });
        this.$router.push("/home/bannerlist");
      }
    },
  },
};
</script>
